<?php

namespace app\common\service\ChannelBusinessService;

use app\common\service\GoodsService\ChannelEsService;
use app\common\service\ProviderService\ServiceProviderService;
use app\model\BbcModel\AuthGroup;
use app\model\BbcModel\BusinessGoods;
use app\model\BbcModel\Goods;
use app\model\BbcModel\GoodsBrand;
use app\model\BbcModel\GoodsClass;
use app\model\BbcModel\GoodsSpecPrice;
use app\model\BbcModel\Manager;
use think\facade\Db;
use app\Normal;
use app\model\BbcModel\ServiceProvider;
use app\model\BbcModel\BusinessLevel;
use app\model\BbcModel\Channel;
use app\model\BbcModel\Store;
use app\model\BbcModel\ChannelBusiness;
use app\model\BbcModel\Order;



/**
 * 渠道商业务
 * @author linan
 */
class BusinessService
{

    /**
     * 新建编辑渠道商等级
     * @param array $param
     * @return array
     */
    public function channelBusinessLevel( array $param )
    {
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"请选择所属大B");
        }
        $channel=Channel::instance()->info(['id'=>$param['cid']]);
        if(empty($channel)){
            return Normal::returnCode(Normal::FAIL,"所选择的大B不存在");
        }
        if(empty($param['level'])){
            return Normal::returnCode(Normal::FAIL,"请输入渠道商等级");
        }
        if(!is_numeric($param['level'])){
            return Normal::returnCode(Normal::FAIL,"渠道商等级需要输入数字");
        }
        $has=BusinessLevel::instance()->info(['level'=>$param['level'],'cid'=>$param['cid']]);
        if($has){
            if((!empty($param['id']) && $has['id']<>$param['id']) || empty($param['id'])){
                return Normal::returnCode(Normal::FAIL,"等级".$param['level'].'已存在');
            }
        }

        if(empty($param['level_name'])){
            return Normal::returnCode(Normal::FAIL,"请输入等级名称");
        }
        if(!empty($param['id'])){
            $old=BusinessLevel::instance()->info(['id'=>$param['id']]);
            if(empty($old)){
                return Normal::returnCode(Normal::FAIL,"编辑的渠道商等级不存在");
            }else{
                $res=BusinessLevel::instance()->edit(['id'=>$old['id']],['level'=>$param['level'],'level_name'=>$param['level_name'],'cid'=>$param['cid'],'content'=>$param['content'],'md'=>time()]);
                if($res){
                    return Normal::returnCode(Normal::SUC,"编辑成功");
                }else{
                    return Normal::returnCode(Normal::FAIL,"编辑失败");
                }
            }
        }else{
            $res=BusinessLevel::instance()->add(['level'=>$param['level'],'level_name'=>$param['level_name'],'content'=>$param['content'],'cid'=>$param['cid'],'md'=>time()]);
            if($res){
                return Normal::returnCode(Normal::SUC,"新增成功");
            }else{
                return Normal::returnCode(Normal::FAIL,"新增失败");
            }
        }
    }

    /**
     * 渠道商等级列表
     * @return array
     */
    public function businessLevelList()
    {

        $list=BusinessLevel::instance()->lists(['_order_'=>'cid asc ,level asc']);
        $channel=Channel::instance()->lists(['_fields_'=>'id,business_name']);
        $channel=array_column($channel,'business_name','id');
        foreach ($list as $k=>$v){
            $list[$k]['master_name']=$channel[$v['cid']];
        }
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }

    /**
     * 渠道商等级详情
     * @param array $param
     * @return array
     */
    public function businessLevelDetail(array $param)
    {

        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数id");
        }
        $info=BusinessLevel::instance()->info(['id'=>$param['id']]);
        $info['channel_name']=Channel::instance()->where(['id'=>$info['cid']])->value('business_name');
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"等级不存在");
        }else{
            return Normal::returnCode(Normal::SUC,"请求成功",$info);
        }
    }

    /**
     * 新增编辑渠道商
     * @param array $param
     * @return array
     */
    public function channelBusiness(array $param)
    {
        if(empty($param['id'])){
            if(empty($param['cid'])){
                return Normal::returnCode(Normal::FAIL,"请选择服务商所属大B");
            }
            $channel=Channel::instance()->info(['id'=>$param['cid']]);
            if(empty($channel)){
                return Normal::returnCode(Normal::FAIL,"所选大B不存在");
            }
            if(empty($param['sp_id'])){
                return Normal::returnCode(Normal::FAIL,"缺少参数服务商id");
            }
            $service=ServiceProvider::instance()->info(['id'=>$param['sp_id']]);
            if(empty($service)){
                return Normal::returnCode(Normal::FAIL,"所选服务商不存在");
            }
        }
        if(empty($param['name'])){
            return Normal::returnCode(Normal::FAIL,"请输入渠道商名称");
        }
        if(empty($param['level_id'])){
            return Normal::returnCode(Normal::FAIL,"请选择渠道商等级");
        }
        $level=BusinessLevel::instance()->info(['id'=>$param['level_id']]);
        if(empty($level)){
            return Normal::returnCode(Normal::FAIL,"所选渠道商等级不存在");
        }
        if(empty($param['mobile'])){
            return Normal::returnCode(Normal::FAIL,"请输入联系方式");
        }
        $mobile=ChannelBusiness::instance()->info(['cid'=>$param['cid'],'mobile'=>$param['mobile']]);
        if(!empty($mobile)){
            if(empty($param['id']) || (!empty($param['id']) && $param['id']<>$mobile['id'])){
                return Normal::returnCode(Normal::FAIL,"联系方式已存在");
            }
        }
        if(empty($param['country'])){
            return Normal::returnCode(Normal::FAIL,"请输入所在地区");
        }
        if(empty($param['card_type'])){
            return Normal::returnCode(Normal::FAIL,"请选择证件类型");
        }
        if(empty($param['card_number'])){
            return Normal::returnCode(Normal::FAIL,"请输入证件号码");
        }
        if(empty($param['card_front'])){
            return Normal::returnCode(Normal::FAIL,"请上传证件照正面");
        }
        if($param['card_type']==1 && empty($param['card_back'])){
            return Normal::returnCode(Normal::FAIL,"请上传证件照反面");
        }
        $param['status']=$param['status']??0;
        $data=[
           'cid'          => $param['cid'],
           'sp_id'        => $param['sp_id'],
           'name'         => $param['name'],
           'wechat'       => $param['wechat']??'',
           'level_id'     => $param['level_id'],
           'card_type'    => $param['card_type'],
           'card_number'  => $param['card_number'],
           'card_front'   => $param['card_front'],
           'card_back'    => $param['card_back']??'',
           'mobile'       => $param['mobile'],
           'country'      => $param['country'],
           'status'       => $param['status'],
           'check_status' => 1,
           'md'           => time(),
            'recommend_name'    => $param['recommend_name']??'',
            'recommend_idcard'  => $param['recommend_idcard']??'',
        ];
        try{
            Db::startTrans();
            if(!empty($param['id'])){
                $info=ChannelBusiness::instance()->info(['id'=>$param['id']]);
                if(empty($info)){
                    return Normal::returnCode(Normal::FAIL,"编辑的渠道商不存在");
                }else{
                    if($param['mobile']<>$info['mobile']){//修改后台登录账号
                        $checkMember = callTcpService('bbcUserAccountRegister',['mobile'=> $info['mobile']]);
                        if($checkMember['code']==200){
                            $mid=$checkMember['data']['mid'];
                        }else{
                            return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$checkMember['msg']);
                        }
                        $channel=Channel::instance()->info(['id'=>$info['cid']]);
                        $has=Manager::instance()->info(['mid'=>$mid,'cb_id'=>$param['id'],'cid'=>$channel['id']]);
                        if($has){
                            $newMember = callTcpService('bbcUserAccountRegister',['mobile'=> $param['mobile']]);
                            if($newMember['code']==200){
                                $new_mid=$newMember['data']['mid'];
                            }else{
                                return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$newMember['msg']);
                            }
                            Manager::instance()->edit(['id'=>$has['id']],['mid'=>$new_mid]);
                        }
                    }
                    unset($data['cid']);
                    unset($data['sp_id']);
                    $res=ChannelBusiness::instance()->edit(['id'=>$info['id']],$data);
                    if($res){
                        Db::commit();
                        return Normal::returnCode(Normal::SUC,"编辑成功");
                    }else{
                        Db::rollback();
                        return Normal::returnCode(Normal::FAIL,"编辑失败");
                    }
                }
            }else{
                $data['cd']=time();
                $data['check_time']=time();
                $data['code']='A'.rand(0000,9999);
                $flag=true;
                while ($flag){
                    $code='A'.rand(0000,9999);
                    $used=ChannelBusiness::instance()->info(['code'=>$code]);
                    if(empty($used)){
                        $flag=false;
                    }
                }
                $data['code']=$code;
                $res=ChannelBusiness::instance()->add($data);
                if($res){
                    Db::commit();
                    return Normal::returnCode(Normal::SUC,"新增成功");
                }else{
                    Db::rollback();
                    return Normal::returnCode(Normal::FAIL,"新增失败");
                }
            }
        }catch (\Exception $e){
            Db::rollback();
            return Normal::returnCode(Normal::FAIL,$e->getMessage());
        }
    }

    /**
     * 渠道商列表
     * @param array $param
     * @return array
     */
    public function channelBusinessList(array $param)
    {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:10;
        $where=[
            '_fields_'=>'id,cid,sp_id,name,level_id,status,check_status,mobile,all_sell,qrcode,code,recommend_name,recommend_idcard',
            '_order_'=>'id desc'
        ];
        if(!empty($param['name'])){
            $where[]=['name','like','%'.$param['name'].'%'];
        }
        if(!empty($param['sp_id'])){
            $where[]=['sp_id','=',$param['sp_id']];
        }
        if(!empty($param['level_id'])){
            $where[]=['level_id','=',$param['level_id']];
        }
        if(isset($param['status']) && $param['status']!==''){
            $where[]=['status','=',$param['status']];
        }
        if(isset($param['check_status']) && $param['check_status']!==''){
            $where[]=['check_status','=',$param['check_status']];
        }
        if(!empty($param['mobile'])){
            $where[]=['mobile','like','%'.$param['mobile'].'%'];
        }
        if(!empty($param['cb_id'])){
            $where[]= ['id','=',$param['cb_id']];
        }
        if(!empty($param['cid'])){
            $where[]=['cid','=',$param['cid']];
        }
        if(!empty($param['search'])){
            $where[]=['mobile|name','like','%'.$param['search'].'%'];
        }
        $list=ChannelBusiness::instance()->listPages($where,$limit,$page);
        $num=ChannelBusiness::instance()->countNum($where);
        $level=BusinessLevel::instance()->lists(['_fields_'=>'id,level_name']);
        $level=array_column($level,'level_name','id');
        $service=ServiceProvider::instance()->lists(['_fields_'=>'id,name']);
        $service=array_column($service,'name','id');
        $channel=Channel::instance()->lists(['_fields_'=>'id,business_name']);
        $channel=array_column($channel,'business_name','id');
        foreach ($list as $k=>$v){
            $list[$k]['channel_name']=$channel[$v['cid']];
            $list[$k]['service_name']=$service[$v['sp_id']];
            $list[$k]['level_name']=$level[$v['level_id']];
            $list[$k]['status_name']=$v['status']==1?'启用':'禁用';
            $list[$k]['check_status_name']=$v['check_status']==1?'已审核':($v['check_status']==2?'审核失败':'待审核');
            $list[$k]['store_number']=Store::instance()->countNum(['cb_id'=>$v['id']]);
            $list[$k]['order_number']=Order::instance()->countNum(['cb_id'=>$v['id'],'pay_status'=>1]);
            $list[$k]['order_money']=$v['all_sell'];
        }
        $data['total']=$num;
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"请求成功",$data);
    }

    /**
     * 渠道商列表下拉菜单
     * @param array $param
     * @return array
     */
    public function channelBusinessSelectList(array $param)
    {
        $where=[
            ['check_status','=',1],
            '_fields_'=>'id,name,mobile',
            '_order_'=>'id desc'
        ];
        if(!empty($param['sp_id'])){
            $where[]=['sp_id','=',$param['sp_id']];
        }
        if(!empty($param['cb_id'])){
            $where[]= ['id','=',$param['cb_id']];
        }
        if(!empty($param['cid'])){
            $where[]=['cid','=',$param['cid']];
        }
        $list=ChannelBusiness::instance()->lists($where);
        return Normal::returnCode(Normal::SUC,"请求成功",$list);
    }

    /**
     * 渠道商详情
     * @param array $param
     * @return array
     */
    public function businessDetail(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数渠道商id");
        }
        $info=ChannelBusiness::instance()->info(['id'=>$param['id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"渠道商不存在");
        }
        $info['cd']=date('Y-m-d H:i:s',$info['cd']);
        $info['level_name']=BusinessLevel::instance()->where(['id'=>$info['level_id']])->value('level_name');
        return Normal::returnCode(Normal::SUC,"请求成功",$info);
    }


    /**
     * 渠道商审核
     * @param array $param
     * @return array
     */
    public function checkBusiness(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数渠道商id");
        }
        if(empty($param['op'])){
            return Normal::returnCode(Normal::FAIL,"操作参数错误");
        }
        $info=ChannelBusiness::instance()->info(['id'=>$param['id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"审核的渠道商不存在");
        }
        ChannelBusiness::instance()->edit(['id'=>$param['id']],['check_status'=>$param['op'],'check_time'=>time()]);
        return Normal::returnCode(Normal::SUC,"操作成功");
    }

    /**
     * 渠道商账号设置
     * @param array $param
     * @return array
     */
    public function editAccount(array $param)
    {
        if(empty($param['cb_id'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数cb_id");
        }
        if(empty($param['account'])){
            return Normal::returnCode(Normal::FAIL,"请输入渠道商账号");
        }
        if(empty($param['pass'])){
            return Normal::returnCode(Normal::FAIL,"请输入渠道商密码");
        }
        $channel=ChannelBusiness::instance()->info(['id'=>$param['cb_id']]);
        if(empty($channel)){
            return Normal::returnCode(Normal::FAIL,"渠道商不存在");
        }
        if($channel['check_status']<>1){
            return Normal::returnCode(Normal::FAIL,"渠道商未通过审核");
        }
        $args = [
            'mobile'   => $channel['mobile'],
        ];
        $checkMember = callTcpService('bbcUserAccountRegister',$args);
        if($checkMember['code']==200){
            $mid=$checkMember['data']['mid'];
        }else{
            return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$checkMember['msg']);
        }
        $has=Manager::instance()->info(['mid'=>$mid,'cb_id'=>$channel['id'],'cid'=>$channel['cid']]);
        $use=Manager::instance()->info(['account'=>$param['account']]);
        if(!empty($has)){
           if($has['account']<>$param['account'] && $use){
               return Normal::returnCode(Normal::FAIL,"账号已被使用");
           }else{
               Manager::instance()->edit(['id'=>$has['id'],'cb_id'=>$param['cb_id']],['account'=>$param['account'],'password'=>md5($param['pass'])]);
               return Normal::returnCode(Normal::SUC,"修改成功");
           }
        }else{
            if($use){
                return Normal::returnCode(Normal::FAIL,"账号已被使用");
            }else{
                $group['name']="超级管理员";
                $group['is_root']=1;
                $group['status']=1;
                $group['cd']=time();
                $group['cid']=$channel['cid'];
                $group['cb_id']=$channel['id'];
                $group_id=AuthGroup::instance()->add($group);
                $manager_data['cid']=$channel['cid'];
                $manager_data['cb_id']=$channel['id'];
                $manager_data['account']=trim($param['account']);
                $manager_data['mid']=$mid;
                $manager_data['password']=md5(trim($param['pass']));
                $manager_data['name']=$channel['name'];
                $manager_data['status']=1;
                $manager_data['group_id']=$group_id;
                $manager_data['cd']=time();
                $manager_data['md']=time();
                Manager::instance()->add($manager_data);
                return Normal::returnCode(Normal::SUC,"修改成功");
            }
        }

    }

    /**
     * 渠道商代理商品列表
     * @param array $param
     * @return array
     */
    public function businessGoodsList(array $param)
    {
        if(empty($param['cb_id'])){
            return Normal::returnCode(Normal::FAIL,"请缺少参数渠道商cb_id");
        }
        $business=ChannelBusiness::instance()->info(['id'=>$param['cb_id']]);
        if(empty($business)){
            return Normal::returnCode(Normal::FAIL,"渠道商不存在");
        }
        $level=BusinessLevel::instance()->where(['id'=>$business['level_id']])->value('level');
        $page=$param['page']??1;
        $limit=$param['limit']??10;
        $where=[
            'bg.level'=> $level,
            'bg.cid'  => $business['cid'],
            'g.df'    => 0,
        ];
        $pageInfo = BusinessGoods::instance()
        ->alias('bg')
        ->join('goods g','g.id=bg.goods_id')
        ->field('bg.id,g.skucode,g.name,g.barcode,g.is_bonded,g.id as goods_id,g.class_id,g.brand_id')
        ->where($where)
        ->order('bg.id desc')
        ->paginate([
            'var_page'  => 'page', //分页变量
            'list_rows' => $limit, //每页数量
            'page'      => $page,
        ])
        ->toArray();
        $data['total']=$pageInfo['total'];
        $class=GoodsClass::instance()->lists(['cid'=>$business['cid'],'_fields_'=>'id,name']);
        $class=array_column($class,'name','id');
        $brand=GoodsBrand::instance()->lists(['cid'=>$business['cid'],'_fields_'=>'id,name']);
        $brand=array_column($brand,'name','id');
        $list = $pageInfo['data'];
        foreach ($list as $k=>$v){
            $list[$k]['class_name']=$class[$v['class_id']]??'';
            $list[$k]['brand_name']=$brand[$v['brand_id']]??'';
            $list[$k]['is_bonded']=Goods::instance()->is_bonded[$v['is_bonded']];
            $price=GoodsSpecPrice::instance()->info(['goods_id'=>$v['goods_id'],'_order_'=>'spec_num asc']);
            $list[$k]['price']=$price['price']??'';
            $list[$k]['price_vip']=$price['price_vip']??'';
        }
        $data['list']=$list;
        return Normal::returnCode(Normal::SUC,"操作成功",$data);
    }


    /**
     * 渠道商分级商品数量
     * @return array
     */
    public function businessLevelGoodsNumber()
    {
        $list=BusinessGoods::instance()
            ->field('level,level_id,cid,count(*) as num')
            ->group('level,cid')
            ->order('cid asc,level asc')
            ->select()
            ->toArray();
        $channel=Channel::instance()->lists(['_fields_'=>'id,business_name']);
        $channel=array_column($channel,'business_name','id');
        $business=BusinessLevel::instance()->lists(['_fields_'=>'id,cid,level_name,level']);
        $map=array_column($list,null,'level_id');
        foreach ($business as $k=>$v){
            $business[$k]['channel_name']=$channel[$v['cid']]??'';
            $business[$k]['num']=$map[$v['id']]['num']??0;
        }
        return Normal::returnCode(Normal::SUC,"操作成功",$business);
    }

    /**
     * 渠道商分级商品授权
     * @param array $param
     * @return array
     */
    public function businessLevelGoodsChoose(array $param)
    {
        if(empty($param['level'])){
            return Normal::returnCode(Normal::FAIL,"请缺少参数渠道商等级level");
        }
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大Bid:cid");
        }
        if(empty($param['skucode'])){
            return Normal::returnCode(Normal::FAIL,"缺少授权商品skucode");
        }
        if(!is_array($param['skucode'])){
            return Normal::returnCode(Normal::FAIL,"授权skucode不是数组");
        }
        $add['level']=$param['level'];
        $add['cid']  =$param['cid'];
        $goods=$allGoods=Goods::instance()->lists(['cid'=>$param['cid'],'df'=>0,'_fields_'=>'id,skucode,name,brand_id,class_id,status']);
        $goods=array_column($goods,'id','skucode');
        $level_id=BusinessLevel::instance()->where(['cid'=>$param['cid'],'level'=>$param['level']])->value('id');
        $add['level_id']=$level_id;
        $insert=[];
        $out=[];
        $insertSku=[];
        $has=BusinessGoods::instance()->lists(['cid'=>$param['cid'],'level'=>$param['level'],'_fields_'=>'id,skucode']);
        $has=array_column($has,'id','skucode');
        foreach ($param['skucode'] as $v){
            if(isset($goods[$v])){
                if(isset($has[$v])){
                    $add['id']=$has[$v];
                }else{
                    if(isset($add['id'])){
                        unset($add['id']);
                    }
                }
                $add['skucode']=$v;
                $insertSku[]=$v;
                $add['goods_id']=$goods[$v];
                $insert[]=$add;
            }else{
                $out[]=$v;
            }
        }
        if(!empty($insert)){
            BusinessGoods::instance()->saveAll($insert);
            $brandList=GoodsBrand::instance()->lists(['_fields_'=>'id,name']);
            $brandList=array_column($brandList,'name','id');
            $esData=[];
            $allGoods=array_column($allGoods,null,'id');
            $list=BusinessGoods::instance()->lists([['level_id','=',$level_id],['skucode','in',$insertSku]]);
            foreach ($list as $v){
                $item=[];
                $item['id']=$v['id'];
                $item['channelID']=$v['level_id'];
                $item['goodsId']=$v['goods_id'];
                $item['name']=$allGoods[$v['goods_id']]['name'];
                $item['classifyID']=$allGoods[$v['goods_id']]['class_id'];
                $item['brandName']=$brandList[$allGoods[$v['goods_id']]['brand_id']];
                $item['isActive']=$allGoods[$v['goods_id']]['status']==1?true:false;
                $esData[]=$item;
            }
            $ChannelEsService=new ChannelEsService();
            $ChannelEsService->pushNew($esData,'channel','insert');
            return Normal::returnCode(Normal::SUC,"操作成功",$out);
        }else{
            return Normal::returnCode(Normal::SUC,"无可授权商品",$out);
        }
    }

    /**
     * 渠道商分级商品授权
     * @param array $param
     * @return array
     */
    public function businessLevelGoodsChooseBak(array $param)
    {
        if(empty($param['level'])){
            return Normal::returnCode(Normal::FAIL,"请缺少参数渠道商等级level");
        }
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大Bid:cid");
        }
        if(empty($param['skucode'])){
            return Normal::returnCode(Normal::FAIL,"缺少授权商品skucode");
        }
        if(!is_array($param['skucode'])){
            return Normal::returnCode(Normal::FAIL,"授权skucode不是数组");
        }
        $add['level']=$param['level'];
        $add['cid']  =$param['cid'];
        //删除原商品

        $goods=$allGoods=Goods::instance()->lists(['cid'=>$param['cid'],'df'=>0,'_fields_'=>'id,skucode,name,brand_id,class_id,status']);
        $goods=array_column($goods,'id','skucode');
        $level_id=BusinessLevel::instance()->where(['cid'=>$param['cid'],'level'=>$param['level']])->value('id');
        $add['level_id']=$level_id;
        $insert=[];
        $out=[];
        $insertSku=[];
        $has=BusinessGoods::instance()->lists(['cid'=>$param['cid'],'level'=>$param['level'],'_fields_'=>'id,skucode']);
        $has=array_column($has,'id','skucode');
        foreach ($param['skucode'] as $v){
            if(isset($goods[$v])){
                if(isset($has[$v])){
                    $add['id']=$has[$v];
                }else{
                    if(isset($add['id'])){
                        unset($add['id']);
                    }
                }
                $add['skucode']=$v;
                $insertSku[]=$v;
                $add['goods_id']=$goods[$v];
                $insert[]=$add;
            }else{
                $out[]=$v;
            }
        }
        if(!empty($insert)){
            BusinessGoods::instance()->saveAll($insert);
            $brandList=GoodsBrand::instance()->lists(['_fields_'=>'id,name']);
            $brandList=array_column($brandList,'name','id');
            $esData=[];
            $allGoods=array_column($allGoods,null,'id');
            $list=BusinessGoods::instance()->lists([['level_id','=',$level_id],['skucode','in',$insertSku]]);
            foreach ($list as $v){
                $item=[];
                $item['id']=$v['id'];
                $item['channelID']=$v['level_id'];
                $item['goodsId']=$v['goods_id'];
                $item['name']=$allGoods[$v['goods_id']]['name'];
                $item['classifyID']=$allGoods[$v['goods_id']]['class_id'];
                $item['brandName']=$brandList[$allGoods[$v['goods_id']]['brand_id']];
                $item['isActive']=$allGoods[$v['goods_id']]['status']==1?true:false;
                $esData[]=$item;
            }
            $ChannelEsService=new ChannelEsService();
            $ChannelEsService->pushNew($esData,'channel','insert');
            return Normal::returnCode(Normal::SUC,"操作成功",$out);
        }else{
            return Normal::returnCode(Normal::SUC,"无可授权商品",$out);
        }
    }

    /**
     * 渠道商分级商品可授权商品列表
     * @param array $param
     * @return array
     */
    public function businessLevelGoodsSelectList(array $param)
    {
        if(empty($param['level'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数渠道商等级level");
        }
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大Bid:cid");
        }
        $list=BusinessGoods::instance()->where(['level'=>$param['level'],'cid'=>$param['cid']])->column('goods_id');
        $param['except_goods']=$list;
        $ServiceProviderService= new ServiceProviderService();
        $res=$ServiceProviderService->channelGoodsList($param);
        return $res;
    }

    /**
     * 渠道商分级商品列表
     * @param array $param
     * @return array
     */
    public function businessLevelGoodsList(array $param)
    {
        if(empty($param['level'])){
            return Normal::returnCode(Normal::FAIL,"请缺少参数渠道商等级level");
        }
        if(empty($param['cid'])){
            return Normal::returnCode(Normal::FAIL,"缺少参数大Bid:cid");
        }
        $page=$param['page']??1;
        $limit=$param['limit']??10;
        $where=[
          'bg.level'=> $param['level'],
          'bg.cid'  => $param['cid'],
        ];
        
        $pageInfo = BusinessGoods::instance()
        ->alias('bg')
        ->join('goods g','g.id=bg.goods_id')
        ->field(implode(",",[
            'bg.id',
            'g.skucode',
            'g.name',
            'g.barcode',
            'g.is_bonded',
            'g.class_id',
            'g.brand_id',
            'g.id as goods_id'
        ]))
        ->where($where)
        ->order('bg.id desc')
        ->paginate([
            'var_page'  => 'page', //分页变量
            'list_rows' => $limit, //每页数量
            'page'      => $page,
        ])
        ->toArray();
        
        $class=GoodsClass::instance()->lists(['cid'=>$param['cid'],'_fields_'=>'id,name']);
        $class=array_column($class,'name','id');
        $brand=GoodsBrand::instance()->lists(['cid'=>$param['cid'],'_fields_'=>'id,name']);
        $brand=array_column($brand,'name','id');
        $list =$pageInfo['data'];
        foreach ($list as $k=>$v){
            $list[$k]['class_name']=$class[$v['class_id']]??'';
            $list[$k]['brand_name']=$brand[$v['brand_id']]??'';
            $list[$k]['is_bonded']=Goods::instance()->is_bonded[$v['is_bonded']];
            $price=GoodsSpecPrice::instance()->info(['goods_id'=>$v['goods_id'],'_order_'=>'spec_num asc']);
            $list[$k]['price']=$price['price']??'';
            $list[$k]['price_vip']=$price['price_vip']??'';
        }
        $data['total']  = $pageInfo['total'];
        $data['list']   = $list;
        return Normal::returnCode(Normal::SUC,"操作成功",$data);
    }


    /**
     * 渠道商分级商品更改
     * @param array $param
     * @return array
     */
    public function businessLevelGoodsChange(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"请缺少参数序号id");
        }
        if(empty($param['skucode'])){
            return Normal::returnCode(Normal::FAIL,"缺少新商品skucde");
        }
        $info=BusinessGoods::instance()->info(['id'=>$param['id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"被修改的商品不存在");
        }
        $goods=Goods::instance()->info(['cid'=>$info['cid'],'skucode'=>$param['skucode'],'df'=>0]);
        if(empty($goods)){
            return Normal::returnCode(Normal::FAIL,"新商品的商品资料不存在");
        }
        $res=BusinessGoods::instance()->edit(['id'=>$param['id']],['skucode'=>$param['skucode'],'goods_id'=>$goods['id']]);
        $brandName=GoodsBrand::instance()->where(['id'=>$goods['brand_id']])->value('name');
        $item['id']=$param['id'];
        $item['channelID']=$info['level_id'];
        $item['goodsId']=$goods['id'];
        $item['name']=$goods['name'];
        $item['classifyID']=$goods['class_id'];
        $item['brandName']=$brandName;
        $item['isActive']=$goods['status']==1?true:false;
        $esData[]=$item;
        $ChannelEsService=new ChannelEsService();
        $ChannelEsService->pushNew($esData,'channel','insert');
        if($res!==false){
            return Normal::returnCode(Normal::SUC,"操作成功");
        }else{
            return Normal::returnCode(Normal::SUC,"操作失败");
        }
    }

    /**
     * 渠道商分级商品删除
     * @param array $param
     * @return array
     */
    public function businessLevelGoodsDelete(array $param)
    {
        if(empty($param['id'])){
            return Normal::returnCode(Normal::FAIL,"请缺少参数序号id");
        }
        $info=BusinessGoods::instance()->info(['id'=>$param['id']]);
        if(empty($info)){
            return Normal::returnCode(Normal::FAIL,"被删除的商品不存在");
        }
        $res=BusinessGoods::instance()->del(['id'=>$param['id']]);
        $esData[]=['id'=>$param['id']];
        $ChannelEsService=new ChannelEsService();
        $ChannelEsService->pushNew($esData,'channel','delete');
        if($res!==false){
            return Normal::returnCode(Normal::SUC,"操作成功");
        }else{
            return Normal::returnCode(Normal::SUC,"操作失败");
        }
    }

    /**
     * 渠道商二维码，登录页
     */
    public function makeChannelBusinessQrcode(array $param):array {
        if(empty($param['cb_id'])){
            return Normal::returnCode(Normal::FAIL,"渠道id不能为空");
        }
        $business=ChannelBusiness::instance()->info(['id'=>$param['cb_id']]);
        $args = [
            'cid'   => $param['cid'],
            'cb_id'   => $param['cb_id'],
            'invited_code'   => $business['code'],
        ];
        if(env('APP_ENV')&&env('APP_ENV')=='dev'){
            return Normal::returnCode(Normal::SUC,"获取成功:",['url'=>'']);
        }
        $checkMember = callTcpService('makeChannelQrcode',$args);        
        if($checkMember['code']==200){
            return Normal::returnCode(Normal::SUC,"获取成功:",$checkMember['data']);
        }else{
            return Normal::returnCode(Normal::FAIL,"SSO服务错误:".$checkMember['msg']);
        }
    }



}

